package com.ruoyi.jksd.controller;

import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.jksd.common.dto.XyUserBalanceDto;
import com.ruoyi.jksd.common.dto.XyUsersPwdDto;
import com.ruoyi.jksd.common.dto.XyuserDZDto;
import com.ruoyi.jksd.domain.XyUsers;
import com.ruoyi.jksd.service.IXyUsersService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 会员-用户Controller
 *
 * @author ruoyi
 * @date 2024-05-26
 */
@RestController
@RequestMapping("/jksd/users")
public class XyUsersController extends BaseController {
    @Autowired
    private IXyUsersService xyUsersService;

    @Autowired
    private ISysUserService userService;

    /**
     * 查询会员-用户列表
     */
//    @PreAuthorize("@ss.hasPermi('jksd:users:list')")
    @GetMapping("/list")
    public TableDataInfo list(XyUsers xyUsers) {
        startPage();
        List<XyUsers> list = xyUsersService.selectXyUsersList(xyUsers);
        return getDataTable(list);
    }

    /**
     * 导出会员-用户列表
     */
//    @PreAuthorize("@ss.hasPermi('jksd:users:export')")
    @Log(title = "会员-用户", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, XyUsers xyUsers) {
        List<XyUsers> list = xyUsersService.selectXyUsersList(xyUsers);
        ExcelUtil<XyUsers> util = new ExcelUtil<XyUsers>(XyUsers.class);
        util.exportExcel(response, list, "会员-用户数据");
    }

    /**
     * 获取会员-用户详细信息
     */
//    @PreAuthorize("@ss.hasPermi('jksd:users:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(xyUsersService.selectXyUsersById(id));
    }

    /**
     * 新增会员-用户
     */
    @Log(title = "会员-用户", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody XyUsers xyUsers) {
        return toAjax(xyUsersService.insertXyUsers(xyUsers));
    }

    /**
     * 修改会员-用户
     */
    @Log(title = "会员-用户", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody XyUsers xyUsers) {
        //不能修改用户名
        XyUsers dbxyUser = xyUsersService.selectXyUsersById(xyUsers.getId() + "");
        xyUsers.setUsername(dbxyUser.getUsername());
        xyUsers.setNickname(dbxyUser.getNickname());
        return toAjax(xyUsersService.updateXyUsers(xyUsers));
    }

    /**
     * 修改会员-用户
     */
    @Log(title = "会员-用户", businessType = BusinessType.UPDATE)
    @PutMapping("/updatePassWord")
    public AjaxResult updatePassWord(@RequestBody XyUsersPwdDto xyUsers) {
        return toAjax(xyUsersService.updatePassWord(xyUsers));
    }

    /**
     * 删除会员-用户
     */
//    @PreAuthorize("@ss.hasPermi('jksd:users:remove')")
    @Log(title = "会员-用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(xyUsersService.deleteXyUsersByIds(ids));
    }

    /**
     * 调整会员余额
     */
//    @PreAuthorize("@ss.hasPermi('jksd:users:remove')")
    @Log(title = "会员-用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/updateBalance")
    public AjaxResult updateBalance(@RequestBody XyUserBalanceDto xyUserBalanceDto) {
        return xyUsersService.updateBalance(xyUserBalanceDto);
    }

    /**
     * 调整会员余额
     */
//    @PreAuthorize("@ss.hasPermi('jksd:users:remove')")
    @Log(title = "会员-用户", businessType = BusinessType.DELETE)
    @DeleteMapping("/dzkd")
    public AjaxResult dzkd(@RequestBody XyuserDZDto xyuserDZDto) {
        return xyUsersService.dzkd(xyuserDZDto);
    }




    /**
     * 前端注册会员-用户
     */
//    @Log(title = "会员-用户", businessType = BusinessType.INSERT)
    @PostMapping("/register")
    public AjaxResult register(@RequestBody XyUsers xyUsers) {
        //添加系统用户信息
        SysUser user = new SysUser();
        user.setPassword(xyUsers.getPwd());
        user.setUserName(xyUsers.getUsername());
        user.setPhonenumber(xyUsers.getTel());
        user.setNickName(xyUsers.getUsername());
        if (!userService.checkUserNameUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (StringUtils.isNotEmpty(user.getPhonenumber()) && !userService.checkPhoneUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (StringUtils.isNotEmpty(user.getEmail()) && !userService.checkEmailUnique(user)) {
            return error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        //TODO 判断邀请码是否正确

//        user.setCreateBy();
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        userService.insertUser(user);
        xyUsers.setNickname(xyUsers.getUsername());
        xyUsers.setInviteCode(xyUsersService.buildInviteCode());
        xyUsers.setCreateTime(new Date());
        return toAjax(xyUsersService.insertXyUsers(xyUsers));
    }


}
